import { reqcate, reqbanner, reqgoods } from "../../request/api"
//状态
const initState ={
    // 1.1初始化数据 
    cates: [],
    // 2.1 初始化轮播数据 
    banner: [],
    //3.1 商品
    goods: [],
    // 4.1 初始化选中的数据下标 
    n: 0
}

//actionType
const TYPES={
    HOME_CHANGE_CATES:"HOME_CHANGE_CATES",
    HOME_CHANGE_BANNER:"HOME_CHANGE_BANNER",
    HOME_CHANGE_GOODS:"HOME_CHANGE_GOODS",
    HOME_CHANGE_N:"HOME_CHANGE_N"
}

//修改state reducer
const reducer = (state=initState,action)=>{
    switch(action.type){
        case TYPES.HOME_CHANEG_CATES:
            return {
                ...state,
                cates: action.cates
            }
        case TYPES.HOME_CHANGE_BANNER:
            return {
                ...state,
                banner:action.banner
            }
        case TYPES.HOME_CHANGE_GOODS:
            return {
                ...state,
                goods:action.goods
            }
        case TYPES.HOME_CHANGE_N:
            return {
                ...state,
                n:action.n
            }
        default:
            return state;
    }
}

//逻辑和异步actions actionCreators
export const actions={
    changeCates:cates=>({type:TYPES.HOME_CHANGE_CATES,cates}),

    requestCates:()=>{
        return (dispatch,getState)=>{
            let cates = getCates(getState())
            if(cates.length > 0){
                return
            }
            reqcate().then(d=>{
                dispatch(actions.changeCates(d.data.list))
            })
        }
    },

    changeBanner:banner=>({type:TYPES.HOME_CHANGE_BANNER,banner}),

    requestBanner:()=>{
        return (dispatch,getState)=>{
            let banner = getCates(getState())
            if(banner.length > 0){
                return
            }
            reqbanner().then(d=>{
                dispatch(actions.changeBanner(d.data.list))
            })
        }
    },

    changeGoods:goods=>({type:TYPES.HOME_CHANGE_GOODS,goods}),

    requestGoods:()=>{
        return (dispatch,getState)=>{
            let goods = getCates(getState())
            if(goods.length > 0){
                return
            }
            reqgoods().then(d=>{
                dispatch(actions.changeGoods(d.data.list))
            })
        }
    },

    changeN:n=>({type:TYPES.HOME_CHANGE_N,n})
}

//导出数据 Selectors
export const getCates=(state)=>state.Home.cates
export const getBanner=(state)=>state.Home.banner
export const getGoods=(state)=>state.Home.goods
export const getN=(state)=>state.Home.n

//展示在页面的数据
export const showGoods = state =>{
    let goods = getGoods(state)
    let n= getN(state)
    return goods.length ===0 ?[]: goods[n].content
}

//导出reduer
export default reducer;